package com.dudu.controller;



import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dudu.model.ResponseModel;
import com.dudu.model.User;
import com.dudu.service.IUserService;
import com.dudu.service.UserService;
import com.dudu.utils.SMSUtil;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.UUID;

@RestController
@CrossOrigin
public class SmsController {
    @Autowired
    private SMSUtil smsUtil;
    @Autowired
//    private UserService userService;
    private IUserService userService;
    @PostMapping("/sendSms")
    public ResponseModel sendSms(@RequestBody Map<String,String> map){
        String phone = map.get("phone");
        String sms = smsUtil.generateSMS(phone);
        Integer code = 500;
        String msg = "failure";
        Object data = null;

        if(!Strings.isNotEmpty(sms)){
            code = 200;
            msg = "success";
            data = sms;
        }
        return new ResponseModel(code,msg,data);
    }

    @GetMapping("/checkSms")
    public ResponseModel checkSms(String phone,String sms){
//        boolean result = smsUtil.validateSMS(phone, sms);
//        Integer code = 500;
//        String msg = "failure";
//        Object data = null;
//        if(result){
//            code = 200;
//            msg = "success";
//
//            User user = userService.findByPhone(phone);
//            data = user;
//            System.out.println(data+"0000000000");
//        }
//
//        return new ResponseModel(code,msg,data);



        boolean result = smsUtil.validateSMS(phone, sms);
        Integer code = 500;
        String msg = "failure";
        Object data = null;
        if(result){
            code = 200;
            msg = "success";

//            User user = userService.findByPhone(phone);

            QueryWrapper<User> wrapper = new QueryWrapper<User>().eq("user_phone",phone);
            User user = userService.getOne(wrapper);
            System.out.println(user);
            if(user !=null){
                data = user;
                return new ResponseModel(code,msg,data);
            }
            User newUser = new User();
            newUser.setUserPhone(phone);
            userService.saveOrUpdate(newUser);
            System.out.println(user);
            System.out.println(data+"0000000000");
        }
        return new ResponseModel(code,msg,data);
    }
}
